﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using EIS.Obj;
using EIS.ServerAdapter;

namespace EIS.Data
{
    public class LogonData
    {

        public UserLogonResponse Logon(string userName, string password)
        {
            var sw = new StringWriter();

            var logon = new UserLogonDTO(userName, password);
            var logOnRequestSerializer = new XmlSerializer(logon.GetType());

            logOnRequestSerializer.Serialize(sw, logon);

            var logOnRequestXml = sw.ToString();
            var url = GlobalVariable.Instance.ServerRootURL + "userLogon";

            var ds = RestAdapter.HttpPost(url, logOnRequestXml);

            var respReader = new StringReader(ds.GetXml());
            var response = new UserLogonResponse();

            var respDeSerializer = new XmlSerializer(response.GetType());
            response = (UserLogonResponse)respDeSerializer.Deserialize(respReader);

            PostLogonProcess(response);
            
            return response;
        }

        public void PostLogonProcess(UserLogonResponse response)
        {
            GlobalVariable.Instance.ActiveFunctionID.Clear();
            if (response.Succeed.ToUpper() != "Y")
            {
                GlobalVariable.Instance.LogonResult = null;
                GlobalVariable.Instance.CurrentToken = null;
                return;
            }

            
            GlobalVariable.Instance.LogonResult = response;
            GlobalVariable.Instance.CurrentToken = response.Token;
            
            if (GlobalVariable.Instance.LogonResult.Layout != null)
            {
                if (GlobalVariable.Instance.LogonResult.Layout.ApplicationLayoutFromServer != null)
                {
                    foreach (var layout in GlobalVariable.Instance.LogonResult.Layout.ApplicationLayoutFromServer)
                    {
                        GlobalVariable.Instance.ActiveFunctionID.Add(layout.FunctionID);

                    }
                }


            }
            //Todo update GlobalVariable
        }
    }
}
